const {callFunc, get, post} = require('./../request')
const config = require('../config');
const fs=require('fs')
const path = require('path');
const runtimeValue = require('./../jsonDb/runtimeValues.json')

//发送消息集成
function sendMsg(params) {
    let data = params.data || params;
    let type = params.type || (params.data && params.data.type);
    return callFunc('SendMsg', {
        toUser: parseInt(data.to),
        sendToType: parseInt(type),
        sendMsgType: data.msgType || "TextMsg",
        content: decodeURIComponent(data.content) || '',
        replayInfo: data.replayInfo || null,
        groupid: parseInt(data.groupId) || 0,
        picUrl: data.picUrl || '',
        voiceUrl: data.voiceUrl || '',
        voiceBase64Buf: "",
        picBase64Buf: "",
        fileMd5: ""
    })
}
//发送XML消息预置模板
function sendXmlMsg(params) {
    //title:文章标题    content:文章正文    sourceTitle:来源于哪儿（默认四川农业大学教务处）  sourceIcon:来源网站图标（默认四川农业大学校徽） Icon：文章配图（默认四川农业大学校徽）
    // brief:在消息列表显示的内容（默认：[通知] 凉菜服务） url:点击消息跳转到哪儿去（默认四川农业大学教务处）
    let {title,content,sourceTitle,sourceIcon,Icon,brief,url}=params.data||params;
    let template=`<?xml version='1.0' encoding='UTF-8' standalone='yes' ?>
    <msg serviceID="1" templateID="1" action="web" brief="${brief||'[通知] 凉菜服务'}" sourceMsgId="0" url="${url||'http://jiaowu.sicau.edu.cn/web/web/web/index.asp'}"
 flag="2" adverSign="0" multiMsgFlag="0">
        <item layout="2" advertiser_id="0" aid="0">
            <picture cover="${Icon||'https://bkimg.cdn.bcebos.com/pic/10dfa9ec8a13632710754f96908fa0ec09fac7ff?x-bce-process=image/resize,m_lfit,w_268,limit_1/format,f_jpg'}" w="0" h="0" />
            <title>${title}</title>
            <summary>${content}</summary>
        </item>
        <source name="${sourceTitle||'四川农业大学教务处'}" icon="${sourceIcon||'https://bkimg.cdn.bcebos.com/pic/10dfa9ec8a13632710754f96908fa0ec09fac7ff?x-bce-process=image/resize,m_lfit,w_268,limit_1/format,f_jpg'}" action="" appid="-1" />
 </msg>`;
    return sendMsg({
        ...params,
        content:template,
        msgType:"XmlMsg"
    })
}
//全体禁言的设置与取消
function shutUpAll(params) {
    let data = params.data || params;
    let open = Boolean(data.open) || false;
    if (!data.groupId) return {msg: '缺少参数，请检查'}
    return callFunc('OidbSvc.0x89a_0', {
        GroupID: parseInt(data.groupId),
        Switch: open == true ? 1 : 0
    })
}

//指定群成员禁言与取消
function shutUp(params) {
    let data = params.data || params;
    if (!data.groupId || !data.memberId) return {msg: '缺少参数，请检查'}
    return callFunc('OidbSvc.0x570_8', {
        GroupID: parseInt(data.groupId),
        ShutUpUserID: parseInt(data.memberId),
        ShutTime: data.minutes || 0
    })
}

//撤回消息(需要配合消息上下文使用)
function revoke(params) {
    let data = params.data || params;
    if (!data.groupId || !data.msgSeq || !data.msgRandom) return {msg: '缺少参数，请检查'}
    return callFunc('RevokeMsg', {
        GroupID: parseInt(data.groupId),
        MsgSeq: parseInt(data.msgSeq),
        MsgRandom: parseInt(data.msgRandom)
    })

}

//发布群公告
function subAnnounce(params) {
    let data = params.data || params;
    if (!data.groupId) return {msg: '缺少参数，请检查'}
    return post(`/v1/Group/Announce?qq=${config.ServerQQ}`, 'post', {
        GroupID: parseInt(data.groupId),
        Title: data.title || "",//标题
        Text: data.content || "",//正文
        Pinned: parseInt(data.type) || 0, // #1为置顶,0为普通公告
        Type: parseInt(data.subType) || 10// #发布类型(10为使用弹窗公告,20为发送给新成员,其他暂未知)
    })
}

//更改群成员身份（管理员设置与取消）
function changeMemberRole(params) {
    let data = params.data || params;
    if (!data.groupId || !data.memberId) return {msg: '缺少参数，请检查'}
    console.log(Boolean(data.admin))
    return callFunc('OidbSvc.0x55c_1', {
        GroupID: parseInt(data.groupId),
        UserID: parseInt(data.memberId),
        Flag: Boolean(data.admin) == true ? 1 : 0
    })
}

//获取好友列表
function getFriendList(params) {
    let data = params.data || params;
    let startIndex = data.startIndex || 0
    return callFunc('GetQQUserList', {
        StartIndex: parseInt(startIndex)
    })
}

//设置群名片
function setGroupCard(params) {
    let data = params.data || params;
    if (!data.groupId || !data.memberId) return {msg: '缺少参数，请检查'}
    return callFunc('ModifyGroupCard', {
        GroupID: parseInt(data.groupId),
        UserID: parseInt(data.memberId),
        NewNick: data.newCard || ''
    })
}

//设置群成员头衔
function setUniqueTitle(params) {
    let data = params.data || params;
    if (!data.groupId || !data.memberId) return {msg: '缺少参数，请检查'}
    return callFunc('SetUniqueTitle', {
        GroupID: parseInt(data.groupId),
        UserID: parseInt(data.memberId),
        NewTitle: data.newTitle || ''
    })
}

//获取任意qq资料
function getUserInfo(params) {
    let data = params.data || params;
    if (!data.qq) return {msg: '缺少参数，请检查'}
    return callFunc('GetUserInfo', {
        UserID: parseInt(data.qq)
    })
}

//获取群列表
function getGroupList(params={}) {
    let data = params.data || params;
    let NextToken = data.NextToken || ''
    return callFunc('GetGroupList', {
        NextToken: NextToken
    })
}

//获取群成员列表
function getMemberList(params) {
    let data = params.data || params;
    let groupId = params.groupId, lastMemberId = params.lastMemberId || 0;
    return callFunc('GetGroupUserList', {
        GroupUin: parseInt(groupId),
        LastUin: parseInt(lastMemberId) || 0
    })
}

//获取登录二维码
function login() {
    return get('/v1/Login/GetQRcode')
}
//群管理
function groupManage(params) {
    let data = params.data || params;
    if (!data.groupId || !data.userId||!data.actionType) return {msg: '缺少参数，请检查'}
    return callFunc('GroupMgr',{
        ActionType:parseInt(data.actionType),
        GroupID:parseInt(data.groupId),
        ActionUserID:parseInt(data.userId),
        Content:data.content||''
    })
}
//处理好友请求
function dealFriendAction(params) {
    let data = params.data || params;
    if (!data.action) return {msg: '缺少参数，请检查'}
    return callFunc('DealFriend',{
        ...params,
        Action:data.action
    })
}
//获取小程序token
function getAppToken() {
    return new Promise((resolve, reject) => {
        let timeOut = new Date().getTime() + 7000 * 1000
        get('https://blog.liucl.cn/api/gettoken', true).then(res => {
            let newValues = {}
            fs.writeFile(path.join(__dirname, '../jsonDb/runtimeValues.json'), JSON.stringify({
                ...runtimeValue,
                access_token: res.data.access_token,
                timeOut,
            }), (err) => {
                if (err) {
                    console.error(err)
                    reject(err)
                }
            })
            resolve({
                access_token: res.data.access_token,
                timeOut,
            })
        })
    })
}

//敏感词过滤
function SenseFilter(content = "") {
    if (content.length < 15) return Promise.resolve({success: false, msg: 'content too short,need not filter'});
    return new Promise(resolve => {
        getAppToken().then(({access_token}) => {
            post('https://api.weixin.qq.com/wxa/msg_sec_check?access_token=' + access_token, {
                content
            }, true).then(res => {
                resolve(res)
            }).catch(err=>{
                console.error(err)
            })
        })
    })
}
function fetchItem(id) {
    return Promise.resolve({
        text: 'kongzhi'
    })
}
module.exports = {
    sendMsg,
    login,
    getAppToken,
    SenseFilter,
    fetchItem,
    sendXmlMsg,
    groupManage,
    changeMemberRole,
    setGroupCard,
    setUniqueTitle,
    subAnnounce,
    dealFriendAction,
    revoke,
    shutUpAll,
    getUserInfo,
    shutUp,
    getFriendList,
    getGroupList,
    getMemberList,
}
